package com.zxq.modbus.msgservice;

import com.zxq.modbus.utils.ModBusCrc;
import com.zxq.modbus.container.LockContainer;
import com.zxq.modbus.container.ModBusChannelContainer;
import com.zxq.modbus.model.PlatformModBusDTO;
import com.zxq.modbus.model.PlatformModBusResult;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;

/**
 * 这里发送的是modbus协议
 */
public class ModBusExchangeService implements IDeviceExchange {

    static ModBusExchangeService modBusExchangeService = new ModBusExchangeService();

    public static ModBusExchangeService getInstance(){
        return modBusExchangeService;
    }

    /**
     * 这一步是与设备交互
     * 因为消息走到这里，都是单排的，所有为了保险起见，我还要再这里走成并行
     * @param platformDTO
     * @return
     */
    @Override
    public PlatformModBusResult platPost(PlatformModBusDTO platformDTO) {
        ChannelHandlerContext channel = ModBusChannelContainer.getChannel(platformDTO.getDeviceId());
        PlatformModBusResult result = new PlatformModBusResult();
        result.setDeviceId(platformDTO.getDeviceId());
        if (channel == null) {
                result.setIsSuccess(false);
                result.setMsg("channel not connect");
                return result;
         }
         byte[] srcPduData = platformDTO.getPduData();
         ModBusCrc modBusCrc = new ModBusCrc();
         modBusCrc.injectSrcBytes(srcPduData);
         if (!modBusCrc.isLegalFrame(srcPduData)) {
                result.setMsg("frame crc error!");
                result.setIsSuccess(false);
                return result;
            }
         ModBusChannelContainer.putModBusCrc(channel, modBusCrc);
         byte[] dstAsduData = LockContainer.lockChannel(channel, srcPduData);
         if (dstAsduData != null) {
                result.setDataResult(dstAsduData);
                result.setMsg("success");
                result.setIsSuccess(true);
            } else {
                result.setMsg("channel no return data");
                result.setIsSuccess(false);
            }
            return result;
        }



}
